package com.desmond.squarecamera;

import com.desmond.squarecamera.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());

        checkPermissions();
    }

    /**
     * 检测权限
     */
    private void checkPermissions() {
        if (verifySelfPermission(SystemPermission.CAMERA) != IBundleManager.PERMISSION_GRANTED) {
            requestPermissions();
        }
    }

    /**
     * 申请权限
     */
    private void requestPermissions() {
        String[] permissions = {
                SystemPermission.CAMERA
        };
        List<String> permissionFiltered = Arrays.stream(permissions)
                .filter(permission -> verifySelfPermission(permission)
                        != IBundleManager.PERMISSION_GRANTED)
                .collect(Collectors.toList());
        requestPermissionsFromUser(permissionFiltered
                .toArray(new String[permissionFiltered.size()]), 0);
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode,
                                                   String[] permissions,
                                                   int[] grantResults) {
        if (permissions == null
                || permissions.length == 0
                || grantResults == null
                || grantResults.length == 0) {
            return;
        }
        for (int grantResult : grantResults) {
            if (grantResult != IBundleManager.PERMISSION_GRANTED) {
                terminateAbility();
                break;
            }
        }
    }
}
